<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AI接口测试工具</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            padding: 20px;
            min-height: 100vh;
        }
        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 10px;
            padding: 30px;
            box-shadow: 0 10px 40px rgba(0,0,0,0.2);
        }
        h1 {
            color: #333;
            margin-bottom: 10px;
            font-size: 28px;
        }
        .subtitle {
            color: #666;
            margin-bottom: 30px;
            font-size: 14px;
        }
        .test-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #667eea;
        }
        .test-section h2 {
            color: #667eea;
            margin-bottom: 15px;
            font-size: 18px;
        }
        .input-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            color: #555;
            font-weight: bold;
        }
        input, textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        textarea {
            min-height: 80px;
            resize: vertical;
        }
        button {
            background: #667eea;
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            transition: all 0.3s;
        }
        button:hover {
            background: #5568d3;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        button:active {
            transform: translateY(0);
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            background: white;
            border-radius: 4px;
            border: 1px solid #ddd;
            max-height: 400px;
            overflow-y: auto;
        }
        .result pre {
            white-space: pre-wrap;
            word-wrap: break-word;
            font-size: 13px;
            line-height: 1.6;
        }
        .success {
            color: #28a745;
            font-weight: bold;
        }
        .error {
            color: #dc3545;
            font-weight: bold;
        }
        .warning {
            color: #ffc107;
            font-weight: bold;
        }
        .info {
            color: #17a2b8;
            font-weight: bold;
        }
        .token-info {
            background: #fff3cd;
            border: 1px solid #ffc107;
            padding: 10px;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        .btn-group {
            display: flex;
            gap: 10px;
            flex-wrap: wrap;
        }
        .btn-secondary {
            background: #6c757d;
        }
        .btn-secondary:hover {
            background: #5a6268;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>🤖 AI接口测试工具</h1>
        <p class="subtitle">帮助诊断后端API问题 - 请先登录系统以获取Token</p>

        <!-- Token信息 -->
        <div class="test-section">
            <h2>🔑 Token信息</h2>
            <div class="token-info">
                <p><strong>当前Token:</strong> <span id="currentToken">未获取</span></p>
                <p><strong>Token长度:</strong> <span id="tokenLength">0</span></p>
            </div>
            <button onclick="getToken()">📋 获取Token</button>
        </div>

        <!-- 测试1: 创建对话 -->
        <div class="test-section">
            <h2>📝 测试1: 创建对话 (POST /api/XunfeiAI/conversation)</h2>
            <div class="input-group">
                <label>SessionID:</label>
                <input type="text" id="sessionId" value="test-session-123">
            </div>
            <div class="input-group">
                <label>消息:</label>
                <input type="text" id="initialMessage" value="你好">
            </div>
            <div class="btn-group">
                <button onclick="testCreateConversation()">🚀 测试创建对话</button>
            </div>
            <div class="result" id="result1"></div>
        </div>

        <!-- 测试2: 普通对话 -->
        <div class="test-section">
            <h2>💬 测试2: 普通对话 (POST /api/XunfeiAI/chat)</h2>
            <div class="input-group">
                <label>消息:</label>
                <input type="text" id="chatMessage" value="你好，请介绍一下你自己">
            </div>
            <div class="btn-group">
                <button onclick="testChat()">🚀 测试普通对话</button>
            </div>
            <div class="result" id="result2"></div>
        </div>

        <!-- 测试3: 流式对话 -->
        <div class="test-section">
            <h2>🌊 测试3: 流式对话 (POST /api/XunfeiAI/chat/stream)</h2>
            <div class="input-group">
                <label>消息:</label>
                <input type="text" id="streamMessage" value="请详细介绍一下仓库管理系统的功能">
            </div>
            <div class="btn-group">
                <button onclick="testStreamChat()">🚀 测试流式对话</button>
            </div>
            <div class="result" id="result3"></div>
        </div>

        <!-- 测试4: 获取分页数据 -->
        <div class="test-section">
            <h2>📊 测试4: 获取分页数据 (POST /api/XunfeiAI/GetPageData)</h2>
            <div class="btn-group">
                <button onclick="testGetPageData()">🚀 测试获取数据</button>
            </div>
            <div class="result" id="result4"></div>
        </div>

        <!-- 后端检查建议 -->
        <div class="test-section">
            <h2>🔍 后端检查建议</h2>
            <div style="line-height: 2;">
                <p><strong>如果所有测试都返回401错误，请检查后端：</strong></p>
                <ol style="margin-left: 20px; margin-top: 10px;">
                    <li>Token验证逻辑是否正确</li>
                    <li>AI接口是否需要特殊权限</li>
                    <li>是否需要在后端配置允许匿名访问这些AI接口</li>
                    <li>检查后端的认证中间件配置</li>
                </ol>
                
                <p style="margin-top: 15px;"><strong>如果返回404错误，请检查后端：</strong></p>
                <ol style="margin-left: 20px; margin-top: 10px;">
                    <li>接口路由是否正确配置</li>
                    <li>控制器方法是否存在</li>
                    <li>API路径拼写是否正确</li>
                </ol>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:9991/';
        let currentToken = '';

        // 获取Token
        function getToken() {
            currentToken = localStorage.getItem('UserToken') || '';
            document.getElementById('currentToken').textContent = currentToken ? 
                `${currentToken.substring(0, 30)}...` : '未找到Token（请先登录系统）';
            document.getElementById('tokenLength').textContent = currentToken.length;
            
            if (!currentToken) {
                showResult('result1', '<span class="error">❌ 未找到Token，请先登录系统！</span>');
            } else {
                showResult('result1', '<span class="success">✅ Token已获取</span>');
            }
        }

        // 显示结果
        function showResult(elementId, content) {
            const element = document.getElementById(elementId);
            element.innerHTML = content;
        }

        // 测试1: 创建对话
        async function testCreateConversation() {
            const sessionId = document.getElementById('sessionId').value;
            const message = document.getElementById('initialMessage').value;
            
            showResult('result1', '<span class="info">⏳ 正在测试...</span>');
            
            try {
                const response = await fetch(`${API_BASE}api/XunfeiAI/conversation`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': currentToken
                    },
                    body: JSON.stringify({ sessionId, message })
                });

                const data = await response.json();
                
                let html = `<p><span class="${response.ok ? 'success' : 'error'}">
                    ${response.ok ? '✅' : '❌'} HTTP状态: ${response.status} ${response.statusText}
                </span></p>`;
                html += `<p><strong>响应数据:</strong></p><pre>${JSON.stringify(data, null, 2)}</pre>`;
                
                showResult('result1', html);
            } catch (error) {
                showResult('result1', `<span class="error">❌ 请求失败: ${error.message}</span>`);
            }
        }

        // 测试2: 普通对话
        async function testChat() {
            const message = document.getElementById('chatMessage').value;
            
            showResult('result2', '<span class="info">⏳ 正在测试...</span>');
            
            try {
                const response = await fetch(`${API_BASE}api/XunfeiAI/chat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': currentToken
                    },
                    body: JSON.stringify({ 
                        message,
                        history: []
                    })
                });

                const data = await response.json();
                
                let html = `<p><span class="${response.ok ? 'success' : 'error'}">
                    ${response.ok ? '✅' : '❌'} HTTP状态: ${response.status} ${response.statusText}
                </span></p>`;
                html += `<p><strong>响应数据:</strong></p><pre>${JSON.stringify(data, null, 2)}</pre>`;
                
                showResult('result2', html);
            } catch (error) {
                showResult('result2', `<span class="error">❌ 请求失败: ${error.message}</span>`);
            }
        }

        // 测试3: 流式对话
        async function testStreamChat() {
            const message = document.getElementById('streamMessage').value;
            
            showResult('result3', '<span class="info">⏳ 正在测试流式对话...</span>');
            
            try {
                const response = await fetch(`${API_BASE}api/XunfeiAI/chat/stream`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': currentToken
                    },
                    body: JSON.stringify({ 
                        message,
                        history: []
                    })
                });

                let html = `<p><span class="${response.ok ? 'success' : 'error'}">
                    ${response.ok ? '✅' : '❌'} HTTP状态: ${response.status} ${response.statusText}
                </span></p>`;

                if (response.ok) {
                    html += '<p><strong>流式响应:</strong></p><pre>';
                    
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let fullContent = '';

                    while (true) {
                        const { done, value } = await reader.read();
                        if (done) break;
                        
                        const chunk = decoder.decode(value);
                        fullContent += chunk;
                    }
                    
                    html += fullContent + '</pre>';
                } else {
                    const errorData = await response.json();
                    html += `<p><strong>错误信息:</strong></p><pre>${JSON.stringify(errorData, null, 2)}</pre>`;
                }
                
                showResult('result3', html);
            } catch (error) {
                showResult('result3', `<span class="error">❌ 请求失败: ${error.message}</span>`);
            }
        }

        // 测试4: 获取分页数据
        async function testGetPageData() {
            showResult('result4', '<span class="info">⏳ 正在测试...</span>');
            
            try {
                const response = await fetch(`${API_BASE}api/XunfeiAI/GetPageData`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': currentToken
                    },
                    body: JSON.stringify({
                        page: 0,
                        rows: 10,
                        total: 0,
                        tableName: 'string',
                        name: 'string',
                        wheres: 'string',
                        order: 'string',
                        export: false,
                        value: 'string',
                        filter: []
                    })
                });

                const data = await response.json();
                
                let html = `<p><span class="${response.ok ? 'success' : 'error'}">
                    ${response.ok ? '✅' : '❌'} HTTP状态: ${response.status} ${response.statusText}
                </span></p>`;
                html += `<p><strong>响应数据:</strong></p><pre>${JSON.stringify(data, null, 2)}</pre>`;
                
                showResult('result4', html);
            } catch (error) {
                showResult('result4', `<span class="error">❌ 请求失败: ${error.message}</span>`);
            }
        }

        // 页面加载时自动获取Token
        window.onload = function() {
            getToken();
        };
    </script>
</body>
</html>



